package com.jml.jdk8.stream;

import org.junit.Test;

public class AutoCloseableTest implements AutoCloseable {

    public void doSomeThing() throws Exception {
        System.out.println("doSomething invoked!");
        throw new Exception();
    }

    @Override
    public void close() throws Exception {
        System.out.println("关闭！");
    }

    @Test
    public void tt() throws Exception {
        //当代码块退出的时候，会自动调用close方法
        //对资源管理来说，可以用这种代替try catch，更优雅的关流关闭资源，
        //后面不用加catch和finally
        try (AutoCloseableTest autoCloseableTest = new AutoCloseableTest()) {
            autoCloseableTest.doSomeThing();
        }
    }

    //最传统的方法，关闭资源文件
    @Test
    public void t1() throws Exception {
        AutoCloseableTest autoCloseableTest = null;
        try {
            autoCloseableTest = new AutoCloseableTest();
            autoCloseableTest.doSomeThing();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            autoCloseableTest.close();
        }
    }
}
